package com.controller;


import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.entity.Dep;
import com.service.DepServiceImpl;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@RestController
@CrossOrigin("*")
@RequestMapping({"/api"})
public class DepController {

    @Autowired
    private DepServiceImpl depService;

    @Value(("${upload.dir}"))
    private String tmp;

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/addDep",method = RequestMethod.POST)
    public ResponseBean addDep(@RequestBody Dep dep){
        int n=depService.addDep(dep);
        ResponseBean bean=null;
        if(n>0){
            String descDir=request.getServletContext().getRealPath("/images");
            File descDirFile=new File(descDir);
            if (descDirFile.exists()==false){
                descDirFile.mkdirs();
            }
            FileUtil.copy(tmp+"/"+dep.getImage(),descDir+"/"+dep.getImage(),true);
            bean=new ResponseBean(200,0,"新增成功");
        }
else{
            bean=new ResponseBean(500,0,"新增失败");

        }

        return bean;

    }

    @RequestMapping({"/searchDep"})
    public ResponseBean searchDep(@RequestParam(defaultValue = "1")int page,@RequestParam(defaultValue = "10")int limit,Integer depId,String depName){
        IPage result=depService.searchDep(page,limit,depId,depName);
        return new ResponseBean(0,result.getTotal(),result.getRecords());
    }


}
